#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <unistd.h>
#include <pthread.h>

pthread_mutex_t mutex;
pthread_cond_t  cond;

void* thr_fn1(void* arg) {
	pthread_mutex_lock(&mutex);
	sleep(15);
	printf("unlocked\n");
	pthread_mutex_unlock(&mutex);
	return NULL;
}

void* thr_fn2(void* arg) {
	struct timespec tsp;
	struct timeval now;
	gettimeofday(&now);
	tsp.tv_sec = now.tv_sec;
	tsp.tv_nsec = now.tv_usec * 1000;
	tsp.tv_sec += 10;

	pthread_mutex_lock(&mutex);
	if (pthread_cond_timedwait(&cond, &mutex, &tsp) == ETIMEDOUT)
		printf("wait failed\n");
	else
		printf("wait success\n");

	if (pthread_mutex_trylock(&mutex) == EBUSY)
		printf("trylock failed\n");
	else
		printf("trylock success\n");

	return NULL;
}

int main() {
	pthread_mutex_init(&mutex, NULL);
	pthread_cond_init(&cond, NULL);

	pthread_t tid;
	pthread_create(&tid, NULL, thr_fn2, NULL);
	pthread_create(&tid, NULL, thr_fn1, NULL);

	pause();

	return 0;
}